var express = require('express');
var router = express.Router();

router.all('/:id(\\d+)/?*', function(req, res, next) {
    var id = parseInt(req.params.id);
    if(!isNaN(id)) {
        req.model.prt_id = id;
        req.pool.acquire(function(err, conn) {
            conn.call('participations.getParticipants', 
                {participation_id: req.model.prt_id}, function(err, result) {
                req.pool.release(conn);
                req.model.participants = result;
                next();
            });
        });
    } else {
        console.log('jui');
        req.model.warningAlerts.push('wrong id');
        req.session.model = req.model;
        res.redirect("/Periodicals/");
    }
});

router.get('/:id(\\d+)/?*', function(req, res, next) {
    req.pool.acquire(function(err, conn) {
        conn.lcall('participations.getFormInfo', {}, function(err, result) {
            req.pool.release(conn);
            req.model.form = result;
            next();
        });
    });
});

router.post('/:id(\\d+)/create', function(req, res) {
    var params = {};
    params.p_participation_id = req.model.prt_id;
    params.p_role_id = req.body.role;
    params.p_person_id = req.body.person;

    req.pool.acquire(function(err, conn) {
        conn.call('participations.createParticipant', params, function(err, result) {
            req.pool.release(conn);

            if(result.error) {
                req.model.dangerAlerts.push(result.error);
            } else {
                req.model.successAlerts.push('Succesfully added')
            }

            req.session.model = req.model;
            res.redirect('/Participations/' + req.model.prt_id);
        });
    });
});

router.get('/:id(\\d+)/:prtcp_id(\\d+)/delete', function(req, res) {
    var id = parseInt(req.params.prtcp_id);
    req.pool.acquire(function(err, conn) {
        conn.call('participations.deleteParticipant', {participant_id: id}, function(err, result) {
            if(result.error) {
                req.model.dangerAlerts.push(result.error);
            } else {
                req.model.successAlerts.push('Succesfully deleted');
            }
            req.session.model = req.model;
            res.redirect('/Participations/' + req.model.prt_id);
        });
    });
})

router.get('/:id(\\d+)/?*', function(req, res) {
    res.render('participation', req.model);
});


module.exports = router;